<template>
  <div class="com-container">
    <div class="com-chart" ref="stock_ref"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
      allData: [],
      chartInstance: null,
      currentIndex: 0,
      timer: null,
    };
  },

  created() {
    window.addEventListener('resize', this.screenAdapter);
    // 注册回调函数
    this.$socket.registerCallBack('stockData', this.getData);
  },

  mounted() {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: 'getData',
      socketType: 'stockData',
      chartName: 'stock',
      value: '',
    });
    this.screenAdapter();
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.screenAdapter);
    clearInterval(this.timer);
    this.$socket.unRegisterCallBack('stockData');
  },

  computed: {
    fontsize() {
      return {
        fontSize: this.titleFontsize + 'px',
      };
    },
  },

  methods: {
    // init chart
    async initChart() {
      this.chartInstance = this.$echarts.init(
        this.$refs['stock_ref'],
        this.theme
      );
      // handle fixed options
      const initOption = {
        title: {
          text: '‖ 库存销售量',
          left: 20,
          top: 20,
        },
      };
      this.chartInstance.setOption(initOption);

      this.chartInstance.on('mouseover', () => {
        clearInterval(this.timer);
      });
      this.chartInstance.on('mouseout', () => {
        this.startInterval();
      });
    },

    // async getData() {
    //   const { data } = await this.$http.get('stock');
    //   this.allData = data;
    //   this.updateChart();
    //   this.startInterval();
    // },
    getData(data) {
      // const { data } = await this.$http.get('stock');
      this.allData = data;
      this.updateChart();
      this.startInterval();
    },

    updateChart() {
      const centerArr = [
        ['18%', '40%'],
        ['50%', '40%'],
        ['82%', '40%'],
        ['34%', '75%'],
        ['66%', '75%'],
      ];
      const colorArr = [
        ['#4FF778', '#0BA82C'],
        ['#E5DD45', '#E8B11C'],
        ['#E8821C', '#E55445'],
        ['#5052EE', '#AB6EE5'],
        ['#23E5E5', '#2E72BF'],
      ];
      const start = this.currentIndex * 5;
      const end = (this.currentIndex + 1) * 5;
      const showData = this.allData.slice(start, end);
      const seriesArr = showData.map((item, index) => {
        return {
          type: 'pie',
          center: centerArr[index],
          hoverAnimation: false, // 鼠标悬浮动画
          labelLine: {
            show: false, // 隐藏指示线
          },
          // 文字位置
          label: {
            position: 'center',
            color: colorArr[index][0],
          },
          data: [
            {
              name: item.name + '\n\n' + item.sales,
              value: item.sales,
              itemStyle: {
                color: new this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  {
                    offset: 0,
                    color: colorArr[index][0],
                  },
                  { offset: 1, color: colorArr[index][1] },
                ]),
              },
            },
            {
              value: item.stock,
              itemStyle: {
                color: '#333843',
              },
            },
          ],
        };
      });
      // handle data options
      const dataOption = {
        series: seriesArr,
      };
      this.chartInstance.setOption(dataOption);
      this.startInterval();
    },

    screenAdapter() {
      const titleFontsize = (this.$refs['stock_ref'].offsetWidth / 100) * 3.6;
      const innerRadius = titleFontsize * 2.5;
      const outterRadius = innerRadius * 1.125;
      const seriesArr = new Array(5).fill({
        type: 'pie',
        radius: [outterRadius, innerRadius],
        label: {
          fontSize: titleFontsize / 2,
        },
      });

      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontsize,
          },
        },
        series: seriesArr,
      };
      this.chartInstance.setOption(adapterOption);
      this.chartInstance.resize();
    },

    startInterval() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.timer = setInterval(() => {
        this.currentIndex++;
        if (this.currentIndex >= this.allData.length / 5) {
          this.currentIndex = 0;
        }

        this.updateChart();
      }, 1500);
    },
  },
  computed: {
    ...mapState(['theme']),
  },
  watch: {
    theme() {
      console.log('主题切换了');
      this.chartInstance.dispose(); // 销毁当前的图表
      this.initChart(); // 重新以最新的主题名称初始化图表对象
      this.screenAdapter(); // 完成屏幕的适配
      this.updateChart(); // 更新图表的展示
    },
  },
};
</script>

<style scoped lang="scss"></style>
